<template>
  <div id="douList">
    <radio_group
      v-if="$store.state.industry.length != 0"
      :radio_values="$store.state.industry[0]"
      v-model="jobKind"
      title="所属行业"
      class="mt_20"
      isSearch="1"
    />
    <section class>
      <div class="btn_group">
        <el-select v-model="value01" class="drop-down">
          <el-option v-for="item in period" :key="item" :value="item" />
        </el-select>

        <el-tooltip effect="light" placement="top" popper-class="mytooltip">
          <div slot="content">
            数据来源：抖音官方的品牌热DOU榜
            <br />数据更新时间：每周二15:00更新
            <br />榜单规则：根据品牌在抖音上视频内容的热度，通过多维度算法计算得出。榜单主要考量因素有：
            <br />视频发布量--计算周期内，品牌相关视频的发布量。
            <br />播放量：计算周期内，品牌相关视频的播放数，播放时长等。
            <br />互动量：计算周期内，包括但不限于点赞量、评论量、回复评论量、分享量、转发量等视频互动量。
            <br />
          </div>
          <img src="@/assets/meng/search_result04.png" alt style="width:16px;height:16px" />
        </el-tooltip>
        <span class="rule">榜单规则说明</span>
         <button @click="generatorImage" class="btn1">
          <span></span>分享
        </button>
        <button @click="export_data" class="btn2">
          <span></span>导出
        </button>
      </div>
    </section>
    <ul
      class="fixedThead"
      ref="fixedThead"
      :class="{'isShow':isFixed}"
      :style="showLeft==true? 'left:222px':'left:98px'"
    >
      <li>排名</li>
      <li>品牌</li>
      <li
        tc
        v-if="orderType == 1 && sort != 0"
        style="  cursor: pointer;"
        @click="sort_fun(false, 0)"
      >
        热度值
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 0">
        热度值
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li
        tc
        v-if="orderType == 1 && sort != 1"
        style="  cursor: pointer;"
        @click="sort_fun(false, 1)"
      >
        涨幅
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 1" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc v-if="orderType == 1 && sort == 1">
        热度值
        <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 1" class="sort" />
        <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
      </li>
      <li tc>操作</li>
    </ul>
    <table class="table"  ref="capture01">
      <thead>
        <tr>
          <th>排名</th>
          <th>品牌</th>
          <th
            v-if="orderType == 1 && sort != 0"
            style="  cursor: pointer;"
            @click="sort_fun(false, 0)"
          >
            热度值
            <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 0">
            热度值
            <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 0" class="sort" />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th
            v-if="orderType == 1 && sort != 1"
            style="  cursor: pointer;"
            @click="sort_fun(false, 1)"
          >
            涨幅
            <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 1" class="sort" />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th v-if="orderType == 1 && sort == 1">
            热度值
            <img src="@/assets/meng/down_up.png" v-if="orderType == 1 && sort == 1" class="sort" />
            <img src="@/assets/meng/no_down_up.png" v-else class="sort" />
          </th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="brand.length != 0">
        <tr v-for="(item, index) in brand" :key="'res' + index" :id="!index?'tr1':''">
          <td>{{ index + 1 }}</td>
          <td>
            <div class="telentName" @click="BrandDetails(item.brandId)" >
              <div class="logo_box">
                <img :src="item.logo" v-if="item.logo" @error="item.logo = ''"/>
                <i v-else>{{item.brandName.slice(0,1)}}</i>
              </div>
              <p
                id="brand"
                @click="BrandDetails(item.brandId)"
                style="cursor: pointer"
              >{{ item.brandName }}</p>
            </div>
          </td>
          <td>
            <p>{{ item.hot }}</p>
          </td>
          <td>
            <img class="rank_icon" src="@/assets/li/top.png" alt v-if="item.increase > 0" />
            <img class="rank_icon" src="@/assets/li/arrows.png" alt v-if="item.increase < 0" />
            <span v-if="item.increase > 0" class="span1">
              {{
              formatRate(item.increase, 2)
              }}
            </span>
            <span v-if="item.increase < 0" class="span2">
              {{
              formatRate(Math.abs(item.increase), 2)
              }}
            </span>
            <span v-if="item.increase === 0">--</span>
          </td>

          <td>
            <div class="detailsBtnwl" @click="BrandDetails(item.brandId)">查看详情</div>
          </td>
        </tr>
      </tbody>
    </table>

    <p class="nothing" v-if="brand.length != 0">我是有底线的～</p>

    <div
      v-loading="loading"
      v-if="loading && !needBuy"
      class="loading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
    ></div>

    <div class="empty" v-if="brand.length === 0 && !loading" style="height: 445px">
        <img src="@/assets/liu/zw.png" />
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      jobKind: '汽车',
      brand: [],
      //周期
      period: [],
      value01: '',
      time: '日榜',
      time1: '',
      page: 1,
      sort: 0,
      orderType: 1, //1降序 0升序
      loading: true,
      needBuy: false,
      startDate: '',
      endDate: '',

      busy: false,
      showLeft: true,
      isFixed: false,
      offsetTop: 0,
    }
  },
  components: {},
  computed: {
    changData() {
      const { jobKind, value01 } = this
      return {
        jobKind,
        value01,
      }
    },
  },

  created() {
    this.getperiod()
  },
  watch: {
    changData(value) {
      this.page = 1
      this.startDate = value.value01.substring(5, 15)
      this.endDate = value.value01.substring(16, 26)
      localStorage.setItem('startDate', this.startDate)
      localStorage.setItem('endDate', this.endDate)
      localStorage.setItem('date', value.value01)
      this.brand = []
      this.searchData()
    },
    '$store.state.left_nav_flag'(old, newOld) {
      this.showLeft = newOld
      if ((newOld = false)) {
        this.setTBBar()
      } else {
        this.setTBBar()
      }
    },
  },
  mounted() {
    window.addEventListener('scroll', this.initHeight)
    window.addEventListener('resize', () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar()
    })
  },
  methods: {
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false
      let nodes = pNode.childNodes
      let newList = []
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i]
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node)
        }
      }
      return newList
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl
        let ulEl = this.$refs.fixedThead
        let tr1 = document.querySelector('#tr1')
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1)
          let liEls = this.getChilds(ulEl)

          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + 'px'
          }
        }
      })
    },
    // 排序
    sort_fun(parm01, parm02) {
      if (parm01) {
        this.orderType = 0
      } else {
        this.orderType = 1
      }
      this.sort = parm02
      this.page = 1
      this.brand = []
      this.searchData()
    },
    //品牌长度
    text() {
      let str = document.getElementById('brand').innerText
      let length = str.length
      if (length > 30) {
        let result = ''
        result = str.substring(0, 30) + '...'
        this.brand = result
      } else {
        this.brand = str
      }
    },
    getperiod() {
      // //周期数
      this.$axios
        .get('api/Brand/Periods')
        .then((res) => {
          if (res.data.code == 0) {
            res.data.data.map((item, ind) => {
              this.period.push(
                `第${item.cycle}期${item.startDate
                  .split(' ')[0]
                  .replace('-', '.')
                  .replace('-', '.')}-${item.endDate
                  .split(' ')[0]
                  .replace('-', '.')
                  .replace('-', '.')}`
              )

              return this.period
            })
            this.value01 = this.period[0]
            this.startDate = this.period[0].substring(5, 15)
            this.endDate = this.period[0].substring(16, 26)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    searchData() {
      this.loading = true
      this.needBuy = false
      let procategoryId
      //品牌分类
      this.$axios
        .get('api/Brand/Classify')
        .then((res) => {
          if (res.data.code == 0) {
            let industry = []
            industry.push(
              res.data.data.map((item, index) => {
                return item.classifyName
              })
            )
            industry.push(
              res.data.data.map((item, index) => {
                return item.id
              })
            )
            this.$store.commit('changeindustryArr', industry)
            this.$store.state.industry[0].map((item, index) => {
              if (item == this.jobKind) {
                procategoryId = this.$store.state.industry[1][index]
              }
            })
          }
          this.loading = true
          this.$axios
            .post('api/Brand/HeatList', {
              ClassifyId: procategoryId,
              startDate: this.startDate,
              endDate: this.endDate,
              page: this.page,
              size: 30,
              orderType: this.orderType,
              orderValue: this.sort,
            })
            .then((res) => {
              if (res.data.code == 0) {
                this.brand = res.data.data
                this.loading = false
                this.needBuy = true
                this.setTBBar()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        })
        .catch((err) => {
          console.log(err)
        })
    },

    BrandDetails(id) {
      let routeUrl = this.$router.resolve({
        path: '/talent_main/brandRoot',

        query: { id },
      })
      window.open(routeUrl.href, '_blank')
    },
    // 导出
     generatorImage() {
      var that = this;
      const loading = this.$loading({
        lock: true,
        text: "导出中...",
        spinner: "el-icon-loading",
        customClass: "customClass"
      });
      var shareContent;
      shareContent = this.$refs.capture01; //需要截图的包裹的（原生的）DOM 对象
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement("canvas"); //创建一个canvas节点
      //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
      var scale = 1;
      canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale * scale; //定义canvas高度 *缩放
      canvas.style.width = width + "px";
      canvas.style.height = height + "px";
      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
      var opts = {
        dpi: window.devicePixelRatio,
        scale: scale, // 添加的scale 参数
        useCORS: true,
        canvas: canvas, //自定义 canvas
        logging: true //日志开关
      };
      html2canvas(shareContent, opts).then(canvas => {
        let str;

        str = `《品牌热DOU榜-${this.timestamp(
          new Date().getTime() / 1000,
          "Y年M月D日"
        )}》.png`;

        canvas.toBlob(
          function(blob) {
            const eleLink = document.createElement("a");
            eleLink.download = str;
            eleLink.style.display = "none";
            // 字符内容转变成blob地址
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
          },
          "image/png",
          1
        );
        loading.close();
      });
    },
    // 文字加replace 数字加\t
    export_data() {
      let that = this
      let str = ''

      str = `排名,品牌,热度值,涨幅\n`

      for (let i = 0; i < that.brand.length; i++) {
        str += `${that.brand[i].rank},${that.brand[i].brandName},${that.brand[i].hot},${that.brand[i].increase}\n`
      }
      var blob = new Blob([str], { type: 'text/plain;charset=utf-8' }) //解决中文乱码问题
      blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type })
      let object_url = window.URL.createObjectURL(blob)
      var link = document.createElement('a')
      link.href = object_url
      let str_name = ''

      str_name = `《品牌热DOU榜-${this.timestamp(
          new Date().getTime() / 1000,
          "Y年M月D日"
        )}》.csv`

      link.download = str_name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      this.isFixed = scrollTop > 180 ? true : false
    },
  },
}
</script>
<style lang='less' scopd>
#douList {
  width: 100%;
  height: 100%;

  .btn_group {
    text-align: right;
    button {
      width: 70px;
      height: 32px;
      border-radius: 4px;
      border: solid 1px #e5e5e5;
      font-size: 14px;
      // line-height: 30px;
      box-sizing: border-box;
      color: #555;
      text-align: center;
    }
     .btn2{
      color:#67ac5b;
      border: 1px solid #67ac5b;
    }
      .btn1{
      margin-right: 10px;
      margin-left:10px;
      span{
        display: inline-block;
        width:14px;
        height:14px;
        background:url('../../../assets/zhao/fenx.png') no-repeat;
        background-size: 100% 100%;
        margin-right: 4px;
        position: relative;
        top:2px;
      }
    }
    .btn2 {
      span{
        display: inline-block;
        width:14px;
        height:14px;
        background:url('../../../assets/zhao/daoc.png') no-repeat;
        background-size: 100% 100%;
        margin-right: 4px;
        position: relative;
        top: 2px;
      }
    }
    .btn1:hover{
      color: #777;
      span{
         background:url('../../../assets/zhao/fenx_h.png') no-repeat;
        background-size: 100% 100%;
      }
    }
    .btn2:hover{
      color: #80be76;
      border-color:#80be76;
      span{
         background:url('../../../assets/zhao/daoc_h.png') no-repeat;
        background-size: 100% 100%;
      }
    }
    .rule {
      font-size: 14px;
      letter-spacing: 0px;
      color: #888888;
    }
    .drop-down {
      display: inline-block;
      float: left;
    }
  }
  #el_select > span {
    margin-right: 0px !important;
  }
  .el-select .el-input__inner {
    width: 246px !important;
  }
  #radio_group .title {
    font-size: 14px;
    letter-spacing: 0px;
    color: #888;
  }
  .table {
    margin-top: 14px;
    text-align: center;
    box-sizing: border-box;
    thead {
      th {
        padding: 0 5px;
        .sort {
          width: 4px;
          height: 10px;
          margin-right: 2px;
        }
      }
      th:nth-child(1) {
        text-align: left;
        padding-left: 55px;
      }
      th:nth-child(2) {
        width: 40%;
        text-align: left;
      }
      th:nth-child(3),
      th:nth-child(5) {
        width: 12%;
      }
    }
  }
  tbody {
    tr {
      height: 78px;

      td:nth-child(1) {
        width: 15%;
        text-align: left;

        padding-left: 63px;
      }
      td:nth-child(2) {
        width: 40%;
        .telentName {
          text-align: left;
          display: flex;
          align-items: center;
          p:nth-of-type(1) {
            font-size: 14px;
            color: #222;
            font-weight: 600;
            cursor: pointer;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
          }
          p:nth-of-type(1):hover {
            color: #ff924b;
          }
          .logo_box{
            width: 50px;
            height: 50px;
            border-radius: 50%;
            overflow: hidden;
            margin-right: 15px;
            img{
              width: 100%;
              height: 100%;
              flex-shrink: 0;
              object-fit: cover;
            }
            i{
              width: 100%;
              height: 100%;
              color: #ffa500;
              background-color: #fff1e8;
              display: flex;
              justify-content: center;
              align-items: center;
              font-style: normal;
              font-size: 20px;
              cursor: pointer;
            }
          }
        }
      }

      td:nth-child(1),
      td:nth-child(3),
      td:nth-child(4) {
        font-size: 15px;
        font-family: DINAlternate-Bold;

        letter-spacing: 0px;
        color: #222222;
      }
    }
    .rank_icon {
      width: 8px;
      height: 12px;
    }
    .span1 {
      color: #ff0000;
    }
    .span2 {
      color: #0077ff;
    }
  }
  .detailsBtnwl:hover {
    color: #ff924b;
    border-color: #ff924b;
  }
  .fixedThead {
    display: none;
    position: fixed;
    top: 60px;
    left: 200px;

    border-radius: 4px;
    font-size: 14px;
    font-weight: 600;
    color: #555;
    background-color: #f5f9ff;
    height: 48px;
    line-height: 48px;
    overflow: hidden;
    z-index: 99;
    font-size: 0;
    li {
      box-sizing: border-box;
      display: inline-block;
      font-size: 14px;
    }
    li:nth-child(1) {
      padding-left: 63px;
    }
    li:nth-child(2) {
      padding-left: 10px;
    }
    // 问号图片
    .remarkImg {
      display: inline-block;
      width: 14px;
      height: 14px;
      vertical-align: middle;
      margin-top: -5px;
    }

    &.isShow {
      display: block;
    }
    .sort {
      width: 5px;
      height: 10px;
      margin-right: 2px;
    }
  }
  [tc] {
    text-align: center;
  }
  [tl] {
    text-align: left;
  }
  [tr] {
    text-align: right;
  }
}
</style>